<?php

namespace app\club\controller;

use app\common\controller\Clubend;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use fast\Http;
use think\Config;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class User extends Clubend
{
    
    /**
     * CUser模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CUser');
        $this->assign('title','俱乐部管理');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index(){
        //当前俱乐部信息
        $clubid = (int)$this->request->param('ids');
        if(empty($clubid)){
            $clubid = Session::get('clubid');
        }else{
            Session::set("clubid", $clubid);
        }
        if($clubid <= 0){
            return $this->redirect('club/index');
        }
    
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total_score = Db::connect("GameDB")->table('club_total_record')->where(['id'=>$clubid])->sum('score');
    
            $total = $this->model
            ->where($where)
            ->where(['clubid'=>$clubid])
            ->count();
    
            $list = $this->model
            ->where($where)
            ->where(['clubid'=>$clubid])
            ->order('honorscore desc')
            ->limit($offset, $limit)
            ->select();
    
            //处理数据
            $uid_arr = $map_user = $user_arr = $u_count = $room_count = $win_count = [];
            foreach ($list as $val){
                $uid_arr[] = $val['uid'];
            }
            $ucount = Db::table('fa_c_annal_score')->field('uid,count(score) as ucount')->where(['clubid'=>$clubid,'score'=>array('gt',0),'uid'=>array('in',$uid_arr)])->group('uid')->select();//大赢家次数
            foreach ($ucount as $val){
                $u_count[$val['uid']] = $val['ucount'];
            }
            $roomcount = Db::table('fa_c_annal_score')->field('uid,count(score) as roomcount')->where(['clubid'=>$clubid,'uid'=>array('in',$uid_arr)])->group('uid')->select();//游戏场次
            foreach ($roomcount as $val){
                $room_count[$val['uid']] = $val['roomcount'];
            }
            $wincount = Db::table('fa_c_annal_score')->field('uid,sum(win) as winsum')->where(['clubid'=>$clubid,'uid'=>array('in',$uid_arr)])->group('uid')->select();//游戏局数
            foreach ($wincount as $val){
                $win_count[$val['uid']] = $val['winsum'];
            }
            $map_user['uid'] = array('in',$uid_arr);
            $user_list = $this->selectTbale($this->GameDBConfig,'user',$map_user,'uid,nickname,head');//用户列表
            foreach ($user_list as $val){
                $user_arr[$val['uid']] = $val;
            }
            foreach ($list as $key=>$val){
                $list[$key]['owner'] = Session::get('owner.uid');//管理员
                $list[$key]['head'] = isset($user_arr[$val['uid']])?$user_arr[$val['uid']]['head']:'-';//用户头像
                $list[$key]['nickname'] = isset($user_arr[$val['uid']])?$user_arr[$val['uid']]['nickname']:'-';//用户昵称
                $list[$key]['ucount'] = isset($u_count[$val['uid']])?$u_count[$val['uid']]:'-';//大赢家次数
                $list[$key]['roomcount'] = isset($room_count[$val['uid']])?$room_count[$val['uid']]:'-';//游戏场次
                $list[$key]['winsum'] = isset($win_count[$val['uid']])?$win_count[$val['uid']]:'-';//游戏局数
            }
            
            $result = array("total" => $total, "rows" => $list,"clubid"=>$clubid,"totalscore"=>$total_score);
    
            return json($result);
        }
        
        $club_info = Db::connect("GameDB")->table('club')->where(['id'=>$clubid])->find();
        $this->assign('club_info',$club_info);
        return $this->view->fetch();
    
    }
    
    /**
     * 加分
     * @author violet
     * @since 2017-12-12
     */
    public function add($ids = 0){
        $row = $this->model->get($ids);
        if (!$row){
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $honorscore = (int)$params['honorscore'];
            if(($honorscore<0) || ($honorscore % 10) != 0){
                $this->error('加分必须为10的正整数倍');
            }
            //游戏服务器数据
            $sreq = [
                'id' => $row->clubid,
                'uid' => $row->uid,
                'score' => $honorscore,
            ];
            //发送给游戏服务器
            $res = Http::get(Config::get('GameDB.api_url').'updateClubMemberScore',$sreq);
            if($res != 'ok')
            {
                $this->error($res);
            }
            $this->success('操作成功');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     * @param int $ids
     * @author violet
     * @since 2017-11-23
     */
    public function del($ids = "")
    {
        if (!$ids){
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $info = Db::table('fa_c_user')->where(['id'=>$ids])->find();
        if(empty($info)){
            $this->error('用户信息不正确');
        }
        //游戏服务器数据
        $sreq = [
            'id' => $info['clubid'],
            'uid' => $info['uid'],
        ];
        //发送给游戏服务器
        $res = Http::get(Config::get('GameDB.api_url').'delClubMember',$sreq);
        if($res != 'ok')
        {
            $this->error($res);
        }
        $this->success('删除成功');
    }

}
